package com.hjqjl.whdemo.net;

import android.content.Context;
import android.text.TextUtils;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hjqjl.whdemo.base.BaseResponseModel;
import com.hjqjl.whdemo.utils.ThrowableMessageUtil;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public abstract class BaseObserver<T extends BaseResponseModel> implements Observer<T> {
    private final Context mContext;
    private String mPortName = "";//用于打印日志的时候显示出请求接口的名称

    public BaseObserver(Context context) {
        this.mContext = context;
    }

    public BaseObserver(Context context, String portName) {
        this.mContext = context;
        if (portName == null) {
            this.mPortName = "";
        } else {
            this.mPortName = portName;
        }
    }

    @Override
    public void onSubscribe(Disposable d) {
        RxManager.getInstance().add(mContext, d);
        onStart(d);
    }

    @Override
    public void onNext(T response) {
        try {
            if (response.net_success()) {
                try {
                    onSuccess(response);
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtils.showShort(mPortName + "数据处理错误");
                }
            } else {
                try {
                    onFailing(response);
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtils.showShort(mPortName + "数据处理错误2");
                }
            }
        } catch (Exception e) {
            ToastUtils.showShort(mPortName + "服务器返回数据失败..");
        }
    }

    @Override
    public void onError(Throwable e) {
        LogUtils.e(mPortName + "请求错误:" + ThrowableMessageUtil.getMessage(e));
        ExceptionHandle.getInstance().handleException(e, mPortName);

        onFailure(e);
        onFinish();
    }

    @Override
    public void onComplete() {
        onFinish();
    }

    /**
     * 网络请求开始
     */
    public void onStart(Disposable d) {
    }

    /**
     * 请网络请求成功返回值正确
     *
     * @param response 返回值
     */
    public abstract void onSuccess(T response);

    /**
     * 网络请求失败
     */
    public void onFailure(Throwable e) {
    }

    /**
     * 网络请求成功但是返回值是错误的
     *
     * @param response 返回值
     */
    public void onFailing(T response) {
        String message = response.getMessage();
        if (TextUtils.isEmpty(message)) {
            ToastUtils.showShort(mPortName + "服务器返回数据失败(success为false)");
        } else {
            ToastUtils.showShort(message);
        }
    }

    /**
     * 网络请求完成（包括成功和失败）
     */
    public void onFinish() {
    }
}
